/**
 * @class common.utils
 * 一些函数集
 * @singleton
 */
define(function (require) {
    function setupAjax() {
        $.ajaxSetup({
            headers: {"X-Requested-With": "XMLHttpRequest"}
        });
    }

    return {
        get: function (params, success, error, type) {
            setupAjax();
            var url, http_params;
            if (_.isString(params)) {
                url = params;
            }
            else {
                params = _.defaults(params, {
                    g: _global.g,
                    m: _global.m,
                    a: _global.a
                });
                url = _global.root;
                if (_global.URL_ROUTER_ON) {
                    url += _.sprintf('%s/%s/%s', params.g, params.m, params.a);
                    if (_global.mp_id) {
                        url += '?mp_id=' + _global.mp_id;
                    }
                }
                else {
                    url += '?g=' + params.g + '&m=' + params.m + '&a=' + params.a;
                    if (_global.mp_id) {
                        url += '&mp_id=' + _global.mp_id;
                    }
                }
                http_params = _.omit(params, ['g', 'm', 'a']);
            }
            $.get(url, http_params, function (resp) {
                if (resp.status == 0) {
                    if (_.isFunction(error)) {
                        error.apply(this, [resp, http_params]);
                    }
                }
                else {
                    if (_.isFunction(success)) {
                        success.apply(this, [resp, http_params]);
                    }
                }
            }, type);
        },
        /**
         * ajax的get方法，是对jquery.get的封装
         * @param {Object} params url参数对象，如:{m:'app',a:'get',id:'1'}
         * @param {Function} success 成功回调函数
         * @param {Function} error 失败回调函数
         */
        _ajaxGet: function (params, success, error) {
            this.get(params, success, error, 'json');
        },
        /**
         * ajax的post方法，是对jquery.post的封装
         * @param {Object} params url参数对象，如:{m:'app',a:'get',id:'1'}
         * @param {Function} success 成功回调函数
         * @param {Function} error 失败回调函数
         */
        _ajaxPost: function (params, success, error) {
            setupAjax();

            var url, http_params;
            if (_.isString(params)) {
                url = params;
            }
            else {
                params = _.defaults(params, {
                    g: _global.g,
                    m: _global.m,
                    a: _global.a
                });
                url = _global.root;
                if (_global.URL_ROUTER_ON) {
                    url += _.sprintf('%s/%s/%s', params.g, params.m, params.a);
                    if (_global.g == 'wap') {
                        url += '?mp_id=' + _global.mp_id;
                    }
                }
                else {
                    url += '?g=' + params.g + '&m=' + params.m + '&a=' + params.a;
                    if (_global.g == 'wap') {
                        url += '&mp_id=' + _global.mp_id;
                    }
                }
                http_params = _.omit(params, ['g', 'm', 'a']);
            }
            $.post(url, http_params, function (resp) {
                if (resp.status == 0) {
                    if (_.isFunction(error)) {
                        error.apply(this, [resp, http_params]);
                    }
                }
                else {
                    if (_.isFunction(success)) {
                        success.apply(this, [resp, http_params]);
                    }
                }
            }, 'json');
        },
        /**
         * checkbox选择
         * @param  {String} btn  全选选择符
         * @param  {String} item 单个选择符
         * @param  {String} ctx  dom区域选择符
         */
        initSelect: function (btn, item, ctx) {
            ctx = _.empty(ctx) ? 'body' : ctx;
            $(ctx).each(function () {
                var $ctx = $(this);
                $(btn, $ctx).click(function () {
                    $(item, $ctx).prop('checked', $(this).prop('checked')).uniform();
                });
                $(item, $ctx).click(function () {
                    var allChecked = true;
                    $(item, $ctx).each(function () {
                        if (allChecked) {
                            allChecked = $(this).prop('checked');
                        }
                    });
                    $(btn, $ctx).prop('checked', allChecked).uniform();
                });
            });
        },
        /**
         * 初始化tab
         * @param  {Object} ctx jquery object
         */
        initTab: function (ctx) {
            if (_.empty(ctx)) {
                ctx = $('body');
            }
            $('.JTab').each(function () {
                var $this = $(this);
                $('.JTabHeader .JItem', $(this)).click(function () {
                    $(this).addClass('active').siblings().removeClass('active');
                    $('.JTabContent .JItem').eq($(this).index()).show().siblings().hide();
                });
            });
        },
        cookie_policy: function (key, val) {
            if (!_.isset(val)) {
                var policy = _.json_decode($.cookie('__POLICY__'));
                return policy[key];
            }
            var policy = _.json_decode($.cookie('__POLICY__'));
            window.policy = policy || {};
            window.policy[key] = _.trim(val);
            $.cookie('__POLICY__', _.json_encode(window.policy), {
                expires: 7,
                path: '/'
            });
        },
        cate_select: function (options) {
            var settings = {
                field: 'J_cate_id',
                top_option: "请选择",
                select: 'J_cate_select'
            };
            if (options) {
                $.extend(settings, options);
            }
            var self = $("." + settings.select),
                pid = self.attr('data-pid'),
                uri = self.attr('data-uri'),
                selected = self.attr('data-selected'),
                grade = self.attr('data-grade'),
                selected_arr = [];

            var cate_sel = self.selector;
            if (selected != undefined && selected != '0') {
                if (selected.indexOf('|')) {
                    selected_arr = selected.split('|');
                }
                else {
                    selected_arr = [selected];
                }
            }
            self.nextAll(cate_sel).remove();
            $('<option value="">--' + settings.top_option + '--</option>').appendTo(self);
            $.getJSON(uri, {id: pid, grade: grade}, function (result) {
                if (result.data) {
                    for (var i = 0; i < result.data.length; i++) {
                        $('<option value="' + result.data[i].id + '">' + result.data[i].name + '</option>').appendTo(self);
                    }
                }
                if (selected_arr.length > 0) {
                    //IE6 BUG
                    setTimeout(function () {
                        self.find('option[value="' + selected_arr[0] + '"]').attr("selected", true);
                        self.trigger('change');
                    }, 1);
                }
            });

            var j = 1;
            $("." + settings.select).unbind('change').live('change', function () {
                var _this = $(this),
                    _pid = _this.val();
                _this.nextAll(cate_sel).remove();
                if (_pid != '') {
                    $.getJSON(uri, {id: _pid, grade: grade}, function (result) {
                        if (result == null) {
                            return;
                        }
                        if (result.data) {
                            if (result.data[0].type == 1 || result.data[0].type == undefined) {
                                var _childs = $('<select class="' + cate_sel.substr(1) + ' mr10" data-pid="' + _pid + '"><option value="">--' + settings.top_option + '--</option></select>')
                                for (var i = 0; i < result.data.length; i++) {
                                    $('<option value="' + result.data[i].id + '">' + result.data[i].name + '</option>').appendTo(_childs);
                                }
                                _childs.insertAfter(_this);
                                if (selected_arr[j] != undefined) {
                                    //IE6 BUG
                                    //setTimeout(function(){
                                    _childs.find('option[value="' + selected_arr[j] + '"]').attr("selected", true);
                                    _childs.trigger('change');
                                    //}, 1);
                                }
                            }
                            else if (result.data[0].type == 2) {
                                var _childs = $('<div class="list"><div class="name">' + result.data[0].name + ': </div><input type="hidden" name="data_id" value="' + result.data[0].id + '" /><input type="text" class="text" name="data" /></div>');
                                _childs.insertAfter(_this.parents('.list'));
                            }
                            j++;
                        }
                    });
                    $('#' + settings.field).val(_pid);
                }
                else {
                    $('#' + settings.field).val(_this.attr('data-pid'));
                }
            });
        },
        loadAddress: function () {
            $('#addressAjaxBox').find('select').change(function () {
                var id = $(this).val();
                var index = $(this).index();
                var sd = ["省份", "市", "区"];
                $('input[name="' + $(this).attr('data-for') + '"]').val($(this).find('option:selected').text());
                if ($(this).next().length < 1) {
                    return false;
                }
                var $this = $(this);

                $.ajax({
                    url: _.U({m: 'user', a: 'addressajax'}),
                    type: 'POST',
                    dataType: 'json',
                    data: {id: id},
                    success: function (result) {
                        if (result.status == 1) {
                            var html = '<option value="">' + sd[index + 1] + '</option>';
                            for (var i = 0; i < result.data.list.length; i++) {
                                html += '<option value="' + result.data.list[i].id + '">' + result.data.list[i].name + '</option>';
                            }
                            $this.next().html(html);
                            for (var j = index + 2; j < $('#addressAjaxBox').find('select').length; j++) {
                                $('#addressAjaxBox').find('select').eq(j).html('<option value="">' + sd[j] + '</option>');
                            }
                        }
                    }
                });
            });
        }
    };
});